﻿namespace PugLib.UI
{
	using System;
	using System.Threading;
    
	/// <summary>
	/// Taken from http://www.aaronlerch.com/blog/2009/09/25/two-components-for-your-toolbox/
	/// </summary>
	public interface IUserInterfaceContext
	{
		void Execute(Action action);
		void ExecuteAndBlock(Action action);
	}

	/// <summary>
	/// Taken from http://www.aaronlerch.com/blog/2009/09/25/two-components-for-your-toolbox/
	/// </summary>
	public class UserInterfaceContext : IUserInterfaceContext
	{
		private readonly SynchronizationContext _syncContext;

		public UserInterfaceContext(SynchronizationContext syncContext)
		{
			/* Ensure the SynchronizationContext passed in is the main UI thread context */
			_syncContext = syncContext;
		}

		#region IUserInterfaceContext Members

		public void ExecuteAndBlock(Action action)
		{
			if (_syncContext != null)
			{
				_syncContext.Send(s => action(), null);
			}
			else
			{
				action();
			}
		}

		public void Execute(Action action)
		{
			if (_syncContext != null)
			{
				_syncContext.Post(s => action(), null);
			}
			else
			{
				ThreadPool.QueueUserWorkItem(s => action(), null);
			}
		}

		#endregion
	}
}